package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.weixin.paleituo.R;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.OrderInvoiceBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.TipsDialog;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 增值税，增加增票资质
 *
 * @author fengzhen
 * @version v1.0, 2018/4/11
 */
public class CompanyAptitudeActivity extends BasePersonActivity {

    @BindView(R.id.tv_name_table_group)
    EditText mTvNameTableGroup;
    @BindView(R.id.tv_num_table_group)
    EditText mTvNumTableGroup;
    @BindView(R.id.tv_address_table_group)
    EditText mTvAddressTableGroup;
    @BindView(R.id.tv_phone_table_group)
    EditText mTvPhoneTableGroup;
    @BindView(R.id.tv_bank_table_group)
    EditText mTvBankTableGroup;
    @BindView(R.id.tv_bank_id_table_group)
    EditText mTvBankIdTableGroup;

    private OrderInvoiceBean mInvoice;
    private Dialog mLoadingDialog;

    private boolean hasChanged = false;
    private TipsDialog mNotSaveDialog;

    /**
     * 跳转修改单位资质
     */
    public static Intent call2CompanyAptitudeActivity(Context context) {
        Intent intent = new Intent(context, CompanyAptitudeActivity.class);
        return intent;
    }

    @Override
    protected View getContentView(Context context) {
        return UIUtils.inflate(this, R.layout.activity_company_aptitude);
    }

    @Override
    protected void initView() {
        super.initView();
    }

    @Override
    protected void initData() {
        super.initData();
        mTvTitle.setText("增票资质");
        getCompanyAptitude();
    }

    @Override
    public void onBackPressed() {
        if (hasChanged) {
            showTipsDialog();
        } else {
            setResult(RESULT_CANCELED);
            finish();
        }
    }

    @OnClick(R.id.btn_save_activity_company_aptitude)
    public void onClickM() {
        updateAptitude();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back_activity_basepersoninfo:
                onBackPressed();
                break;
        }
    }

    @OnTextChanged(callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED,
            value = {R.id.tv_name_table_group, R.id.tv_num_table_group, R.id.tv_address_table_group,
                    R.id.tv_phone_table_group, R.id.tv_bank_table_group, R.id.tv_bank_id_table_group})
    public void onTextChanged(Editable e) {
        hasChanged = true;
    }

    /**
     * 获取公司资质
     */
    private void getCompanyAptitude() {
        Observable observable = ApiUtils.getApi().getInvoiceGroupInfo(BaseApplication.getToken(), BaseApplication.getUserId())
                .compose(RxHelper.getObservaleTransformer())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mLoadingDialog == null) {
                            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(CompanyAptitudeActivity.this, "");
                        }
                        mLoadingDialog.show();
                    }
                }).subscribeOn(AndroidSchedulers.mainThread());
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<OrderInvoiceBean>(CompanyAptitudeActivity.this) {
            @Override
            protected void _onNext(StatusCode<OrderInvoiceBean> registerProBeanStatusCode) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                mInvoice = registerProBeanStatusCode.getData();
                if (mInvoice != null) {
                    mTvNameTableGroup.setText(mInvoice.getName());
                    mTvNumTableGroup.setText(mInvoice.getNumber());
                    mTvAddressTableGroup.setText(mInvoice.getAddress());
                    mTvPhoneTableGroup.setText(mInvoice.getPhone());
                    mTvBankTableGroup.setText(mInvoice.getBlank());
                    mTvBankIdTableGroup.setText(mInvoice.getAccount());
                }
                hasChanged = false;
            }

            @Override
            protected void _onError(String message) {
                ToastUtils.makeText(message);
                LoadingDialogUtils.closeDialog(mLoadingDialog);
            }

        }, "", lifecycleSubject, false, true);
    }

    /**
     * 更新资质
     */
    private void updateAptitude() {
        String name = mTvNameTableGroup.getText().toString();
        String number = mTvNumTableGroup.getText().toString();
        String address = mTvAddressTableGroup.getText().toString();
        String phone = mTvPhoneTableGroup.getText().toString();
        String bank = mTvBankTableGroup.getText().toString();
        String bankId = mTvBankIdTableGroup.getText().toString();
        if (TextUtils.isEmpty(name)) {
            ToastUtils.makeText("单位名称不能为空");
            return;
        }
        if (TextUtils.isEmpty(number)) {
            ToastUtils.makeText("纳税人识别号不能为空");
            return;
        }
        if (TextUtils.isEmpty(address)) {
            ToastUtils.makeText("注册地址不能为空");
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.makeText("注册电话不能为空");
            return;
        }
        if (TextUtils.isEmpty(bank)) {
            ToastUtils.makeText("开户银行不能为空");
            return;
        }
        if (TextUtils.isEmpty(bankId)) {
            ToastUtils.makeText("银行账号不能为空");
            return;
        }

//        mInvoice.setName(name);
//        mInvoice.setNumber(number);
//        mInvoice.setAddress(address);
//        mInvoice.setPhone(phone);
//        mInvoice.setBlank(bank);
//        mInvoice.setAccount(bankId);

        Observable<StatusCode<Object>> observable = ApiUtils.getApi().saveCompanyAptitude(
                BaseApplication.getToken(),
                BaseApplication.getUserId(),
                name, number, address, phone, bank, bankId
        );
        HttpUtil.getInstance().toSubscribe(observable,
                new ProgressSubscriber<Object>(this) {
                    @Override
                    protected void _onNext(StatusCode<Object> objectStatusCode) {
                        ToastUtils.makeText("增票资质保存成功");
                        finish();
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUtils.makeText(message);
                    }
                }, "", lifecycleSubject, false, true);
    }

    /**
     * 未保存信息提示
     *
     * @author fengzhen
     * @version v1.0, 2018/3/28
     */
    private void showTipsDialog() {
        if (mNotSaveDialog == null) {
            mNotSaveDialog = new TipsDialog.Builder(this)
                    .setCancelClickListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            mNotSaveDialog.dismiss();
                        }
                    })
                    .setContentView("修改的内容还未保存，确认现在返回吗？")
                    .setLeftButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mNotSaveDialog.dismiss();
                        }
                    })
                    .setRightButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mNotSaveDialog.dismiss();
                            setResult(RESULT_CANCELED);
                            finish();
                        }
                    })
                    .build();
        }
        mNotSaveDialog.show();
    }
}
